package com.utilities.parsers.ecocyc.classesParser;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.LinkedList;

import com.utilities.parsers.ecocyc.classesParser.ParseEvents.EventTypes;

public class ParseClassFileParser   
{
	private EventTypes type = null;
	private RandomAccessFile accessFile = null;
	
	private LinkedList<ParseListener> eventListeners = new LinkedList<ParseListener>();
	
	public void addListener(ParseListener parseListener)
	{
		eventListeners.add(parseListener);
	}
	
	private void fireEvent(ParseEvents parseEvent)
	{
		for (ParseListener listener : eventListeners)
		{
			listener.handleEvent(parseEvent);
		}
	}
	
	public void parse(File file) throws IOException
	{
		accessFile = new RandomAccessFile(file, "r");
		fireEvent(new ParseEvents(null,EventTypes.docStarted));
		String readLine = accessFile.readLine();
		while(readLine != null)
		{
			readLine = readLine.trim();
			if (readLine.startsWith("#"))
			{
				type = EventTypes.filecommentLine;
				fireEvent(new ParseEvents(readLine, type));
			}
			else if (readLine.startsWith("UNIQUE-ID"))
			{
				type = EventTypes.uniqueIdLine;
				fireEvent(new ParseEvents(readLine, type));
			}
			else if (readLine.startsWith("TYPES"))
			{
				type = EventTypes.typesLine;
				fireEvent(new ParseEvents(readLine, type));
			}
			else if (readLine.startsWith("COMMON-NAME"))
			{
				type = EventTypes.commonNameLine;
				fireEvent(new ParseEvents(readLine, type));
			}
			else if (readLine.startsWith("COMMENT"))
			{
				type = EventTypes.entrycomment;
				fireEvent(new ParseEvents(readLine, type));
			}
			else if (readLine.startsWith("//"))
			{
				type = EventTypes.entrySeparator;
				fireEvent(new ParseEvents(readLine, type));
			}
			else if (readLine.startsWith("/"))
			{
				type = EventTypes.entrycommentnewLine;
				fireEvent(new ParseEvents(readLine, type));
			}
			readLine = accessFile.readLine();
//			System.out.println(readLine);
		}
		accessFile.close();
		fireEvent(new ParseEvents(null,EventTypes.docEnded));
	}
}
